import pandas as pd
from pathlib import Path
from typing import Set, Dict, List

class FileManager:
    @staticmethod
    def load_known_words(dirs: List[Path]) -> Set[str]:
        """从多个目录加载已知词汇"""
        known = set()
        for dir_path in dirs:
            for xlsx in dir_path.glob('*.xlsx'):
                df = pd.read_excel(xlsx, sheet_name=None, usecols=[0],
                                 header=None, names=['word'])
                for sheet in df.values():
                    known.update(sheet['word'].str.lower().dropna().astype(str))
        return known


    @staticmethod
    def save_results(results: Dict[str, List], output_path: Path):
        """智能保存结果（处理空数据情况）"""
        if not results:
            raise ValueError("无有效词汇数据需要保存")

        try:
            with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
                for sheet_name, data in results.items():
                    if not data:  # 跳过空章节
                        continue

                    df = pd.DataFrame(data, columns=['Word', 'Count', 'Example'])
                    df.sort_values(['Count', 'Word'], ascending=[False, True], inplace=True)
                    df.to_excel(writer, sheet_name=sheet_name[:31], index=False)

                # 确保至少有一个工作表
                if not writer.sheets:
                    pd.DataFrame(['无有效词汇']).to_excel(
                        writer,
                        sheet_name='Empty',
                        header=False
                    )
        except Exception as e:
            # 清理无效文件
            if output_path.exists():
                output_path.unlink()
            raise
